package com.yinhe.music.yhmusic.utils;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.application.AppCache;
import com.yinhe.music.yhmusic.constants.Extras;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.network.NetworkManager;
import com.yinhe.music.yhmusic.network.response.ResponseTransformer;
import com.yinhe.music.yhmusic.network.schedulers.SchedulerProvider;
import com.yinhe.music.yhmusic.personal.model.UpdateInfo;

import io.reactivex.disposables.Disposable;

public class UpdateUtils {
    public static Disposable checkUpdate(final Activity activity, final boolean showToast) {
        return NetworkManager.getWebService().getAppUpdateInfo()
                .compose(ResponseTransformer.handleResult())
                .compose(SchedulerProvider.getInstance().applySchedulers())
                .subscribe(updateInfo -> {
                    if (!activity.isFinishing()) {
                        if (updateInfo.upgrade == 1) {
                            updateDialog(activity, updateInfo).show();
                        } else {
                            if (showToast) {
                                Toast.makeText(activity, "暂时没有检测到新版本", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }, throwable -> {
                    Toast.makeText(activity, throwable.getMessage(), Toast.LENGTH_SHORT).show();
                });
    }


    public static void goToMarket(Context context, String packageName) {
        Uri uri = Uri.parse("market://details?id=" + packageName);
        Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
        try {
            context.startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    //(%2$sMB)

    private static AlertDialog.Builder updateDialog(final Activity activity, final UpdateInfo updateInfo) {
        MLog.debug("update", "info:" + updateInfo.info.replaceAll("\\\\n", "\\\n"));
        //
        String message = String.format("v %1$s\n\n%2$s", updateInfo.newversion, updateInfo.info.replaceAll("\\\\n", "\\\n"));
        AlertDialog.Builder builder = new AlertDialog.Builder(activity)
                .setTitle("发现新版本")
                .setMessage(message)
                .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UmengEventUtils.clickUpdate(activity);
                        download(activity, updateInfo);
                    }
                })
                .setNegativeButton("稍后提醒", null);
        return builder;
    }

    private static void download(Activity activity, UpdateInfo updateInfo) {
        String fileName = String.format("snowmusic_%s.apk", updateInfo.newversion);
        DownloadManager downloadManager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(updateInfo.url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(activity.getString(R.string.app_name));
        request.setDescription("正在更新…");
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setMimeType(MimeTypeMap.getFileExtensionFromUrl(updateInfo.url));
        request.allowScanningByMediaScanner();
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        request.setAllowedOverRoaming(false);
        long id = downloadManager.enqueue(request);
        AppCache.getDownloadList().put(id, Extras.DOWNLOAD_UPDATE);
        ToastUtils.show("正在后台下载");
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            MLog.debug("VersionInfo", "Exception", e);
        }
        return versionName;
    }
}
